import { ref } from 'vue'
import { defineStore } from 'pinia'
import {getAddressListAPI} from '@/API/address'
import { addAddressAPI,deleteAddressAPI,updateAddressAPI } from '@/API/address'
import { useUserStore } from '@/stores/user'
import { showToast } from 'vant'
import router from '@/router'

export const useAddressStore = defineStore('address', () => {
  

 const list =ref<any>([])
 
 //获取地址列表数据
 const setAddList =async () =>{
  const res = await getAddressListAPI(userStore.info.userid)
  list.value=res.data.map((item: { id: any; addressid: any; address: any; province: any; city: any; county: any; addressDetail: any })=>{
    item.id= item.addressid
    item.address=item.province+item.city+item.county+item.addressDetail
    return  item
 })
 
 }

//新增地址
const userStore = useUserStore()
const addAddress=async(data:any)=>{
  const res: any = await addAddressAPI(data)
  if (res.code === '200') {
    showToast({
      type: 'success',
      message: res.message
    })
    //新增成功之后同步到store仓库
    setAddList()

    setTimeout(() => {
      router.push('/address')
    }, 2000)
  }



}

//删除地址
const deleteAddress=async(addressid:any) => {

 const res:any=await deleteAddressAPI(addressid)
  console.log(res);
  
 if (res.code === '200') {
  showToast({
    type: 'success',
    message: '删除成功'
  })
  //新增成功之后同步到store仓库
  setAddList()

  setTimeout(() => {
    router.push('/address')
  }, 2000)
}

}

//更新地址
const updateAddress=async(data:any)=>{
 const res:any=await updateAddressAPI(data)
 if (res.code === '200') {
  showToast({
    type: 'success',
    message: '修改成功'
  })
  //新增成功之后同步到store仓库
  setAddList()

  setTimeout(() => {
    router.push('/address')
  }, 2000)
}
 
}


  return {
    setAddList,
    list,
    addAddress,
    deleteAddress,
    updateAddress
   }
},
{
  persist: true,
})
